<?php
// 本类由系统自动生成，仅供测试用途
namespace Admin\Controller;
use Think\Controller;
class OrderController extends Controller {
  /**
   * 订单列表
   */
  public function OrderListIndex() {
    $adminId = $this->Islogin();
    if(!empty(I('post.getall'))&&I('post.getall')=='aj'){
      $order_db = D('order');
      $order_data = $order_db->ListFieldData(true);
      echo json_encode($order_data['data']);
      return;
    }else{
      $order_db = D('order');
      $order_data = $order_db->ListFieldData(false);
      if($order_data){
        $page = $order_data['page'];
        $this->assign('order_data',$order_data['data']);
        $this->assign('page',$page->show());
      }
      $this->display('orderlist');
    }
  }

  /**
   * 风控待审核的订单总数
   */
  public function OrderCount(){
     $this->Islogin();
    echo M('order')->where('status=0')->count();
  }

  /**
   * 所有的订单
   */
  public function allOrderList() {
     $this->Islogin();
    $order_db = D('order');
    $order_data = $order_db->AllFkOrder();
    if($order_data){
      $page = $order_data['page'];
      $this->assign('order_data',$order_data['data']);
      $this->assign('page',$page->show());
    }
    $this->display('allorderlist');
  }
  /**
   * 所有的订单
   */
  public function allOrderdata() {
     $this->Islogin();
    $order_db = D('order');
    $order_data = $order_db->AllFkOrder();
    if($order_data){
      $page = $order_data['page'];
      $this->assign('order_data',$order_data['data']);
      $this->assign('page',$page->show());
    }
    $this->display("allorderdatas");
  }
  /**
   * 订单详情
   */
  public function OrderDetailsinfo() {
    $this->Islogin();
    $orderid  = $_GET['orderid'];
    $order_db = D('order');
    $user_db  = D('customer');
    if(!$orderid){
      HttpStatus('404');
    }
    $order_data = $order_db->OrderInfo($orderid);
    $user_data = $user_db->UserInfo($order_data['uid']);
    $income_money_arr = ['1'=>'10001以上','2'=>'8001-10000','3'=>'5001-8000','4'=>'4001-5000','5'=>'3001-4000','6'=>'2001-3000','7'=>'1001-2000','8'=>'1000以下'];
    $incomearr = ['1'=>'自己有房','2'=>'房屋按揭','3'=>'自己租房住','4'=>'和父母同住'];
    $user_data['housingnature'] = $incomearr[$user_data['housingnature']];
    $user_data['income'] = $income_money_arr[$user_data['income']];
    if($user_data){
       $user_data['identify_url']=serializeMysql($user_data['identify_url'],1);
       $user_data['driver_url']=serializeMysql($user_data['driver_url'],1);
       $user_data['workproof_url']=serializeMysql($user_data['workproof_url'],1);
       $user_data['bankflow_url']=serializeMysql($user_data['bankflow_url'],1);
       $user_data['creditreport_url']=serializeMysql($user_data['creditreport_url'],1);
       $user_data['otherdata_url']=serializeMysql($user_data['otherdata_url'],1);
       $user_data['identify_url']    = getPublicdian($user_data['identify_url']);
       $user_data['driver_url']      = getPublicdian($user_data['driver_url']);
       $user_data['workproof_url']   = getPublicdian($user_data['workproof_url']);
       $user_data['bankflow_url']    = getPublicdian($user_data['bankflow_url']);
       $user_data['creditreport_url']= getPublicdian($user_data['creditreport_url']);
       $user_data['otherdata_url']   = getPublicdian($user_data['otherdata_url']);
    }
    $user_data['oss_url'] = C('OSSURL');
    $this->assign('order_data',$order_data);
    $this->assign('workproofcount',count($user_data['workproof_url']));
    $this->assign('bankflowcount',count($user_data['bankflow_url']));
    $this->assign('creditreportcount',count($user_data['creditreport_url']));
    $this->assign('otherdatacount',count($user_data['otherdata_url']));
    $this->assign('user_data',$user_data);
    $this->display('orderdetails');
  }
  
  /**
   * 订单管理数据
   */
  public function adminOrderList() {
    $this->Islogin();
    $order1 = D('Order');
    $data  = session('lampzuo_id');
    $res   = $order1 -> getAdminOrderList($data);
    $this->ajaxReturn($res);
  }
  
  /**
   * 财务返回信息
   */
  public function OrderPayConfirm() {
    $this->Islogin();
    $order_mdb = D('order');
    $order_data = $order_mdb->OrderAlreadyPay();
    $page = $order_data['page'];
    $page->setConfig('header','个会员');
    $this->assign('order_data',$order_data['data']);
    $this->assign('show',$page->show);
    $this->display('orderpayconfirm');
  }

  /**
   * 财务导出Excle数据
   */
  public  function ExcleFinance(){
    $data = I('post.');
    $order_mdb = D('order');
    $datas=[];
    if($data['exportType'] == 1){
      $order_data = $order_mdb->OrderAlreadyPay();
      foreach($order_data['data'] as $val){
        $data=array();
        $data[]=$val['contract'];
        $data[]=$val['pay_time'];
        $data[]=$val['firstpaymonthpay'];
        $data[]=$val['customername'];
        $data[]=$val['bank'];
        $data[]=$val['banker'];
        $data[]=$val['banknum'];
        $data[]=$val['actionname'];
        $data[]=$val['GWname'];
        $data[]=$val['provinceid'];
        $data[]=$val['cityname'];
        $data[]=$val['orderid'];
        $data[]=$val['cartype'];
        $data[]=$val['jdc_price'];
        $data[]=$val['statustext'];
        $datas[]=$data;
      }
      $filename_n = date('YmdHis');
      $title=['合同编号','支付时间','支付金额','客户姓名','银行名称','银行账户名','银行卡号','手续员姓名','顾问姓名','所属省份','所属城市','订单编号','车型','筋斗价','状态'];
      $filename_exce = "sheet";
        // 生成Excel并返回文件名称
      $filename = ExportExcelTable($title,$datas,$filename_exce,$filename_n,'./Public/Uploads/ChannelCount/');
      exit(json_encode(['success'=>'OK','filename'=>$filename_n,'message'=>$filename_n.'导出成功！']));
    }else if ($data['exportType'] == 2) {
      $order_data = $order_mdb->OrderHistoryFinance();
      foreach($order_data['data'] as $val){
        $data=array();
        $data[]=$val['orderid'];
        $data[]=$val['cardata']['carnum'];
        $data[]=$val['userdata']['fullanme'];
        $data[]=$val['userdata']['bank'];
        $data[]=$val['userdata']['banker'];
        $data[]=$val['userdata']['banknum'];
        $data[]=$val['cardata']['first_pay'];
        $data[]=$val['cardata']['month_pay'];
        $data[]=$val['orderPaydata']['pay_month'];
        $data[]=$val['orderPaydata']['money'];
        $data[]=$val['orderPaydata']['pay_time'];
        $data[]=$val['cardata']['name'];
        $datas[]=$data;
      }
      $filename_n = date('YmdHis');
      $title=['订单号','车辆编号','客户姓名','银行名称','银行账户名','银行卡号','服务费','月租金','已还期数','下次还款金额','下次还款时间','车辆名称'];
      $filename_exce = "sheet";
      // 生成Excel并返回文件名称
      $filename = ExportExcelTable($title,$datas,$filename_exce,$filename_n,'./Public/Uploads/ChannelCount/');
      exit(json_encode(['success'=>'OK','filename'=>$filename_n,'message'=>$filename_n.'导出成功！']));
    }else if($data['exportType'] == 3){
      $order_data =  $order_mdb->getWaynumMoney();
      foreach($order_data as $val){
        $data=array();
        $data[]=$val['waynum'];
        $data[]=$val['orderid'];
        $data[]=$val['Waystatus']==3?'已关闭':'激活';
        $data[]=$val['name'];
        $data[]=$val['bank'];
        $data[]=$val['banker'];
        $data[]=$val['banknum'];
        $data[]=$val['money'];
        $data[]= $val['status']== 0?'未打款':'已打款';
        $datas[]=$data;
      }
      $filename_n = date('YmdHis');
      $title=['渠道编号','订单号','渠道状态','渠道姓名','渠道银行名称','渠道银行户主','渠道银行卡号','打款金额','打款状态'];
      $filename_exce = "sheet";
      // 生成Excel并返回文件名称
      $filename = ExportExcelTable($title,$datas,$filename_exce,$filename_n,'./Public/Uploads/ChannelCount/');
      exit(json_encode(['success'=>'OK','filename'=>$filename_n,'message'=>$filename_n.'导出成功！']));
    }else if($data['exportType'] == 4){
        $order_data =  $order_mdb->getWaynumList();
        foreach($order_data as $val){
        $data=array();
        $data[]=$val['waynum'];
        $data[]=$val['orderid'];
        $data[]=$val['Waystatus']==3?'已关闭':'激活';
        $data[]=$val['name'];
        $data[]=$val['bank'];
        $data[]=$val['banker'];
        $data[]=$val['banknum'];
        $data[]=$val['money'];
        $data[]= $val['status']== 0?'未打款':'已打款';
        $data[]= $val['username'];
        $datas[]=$data;
      }
      $filename_n = date('YmdHis');
      $title=['渠道编号','订单号','渠道状态','渠道姓名','渠道银行名称','渠道银行户主','渠道银行卡号','打款金额','打款状态','打款人姓名'];
      $filename_exce = "sheet";
      // 生成Excel并返回文件名称
      $filename = ExportExcelTable($title,$datas,$filename_exce,$filename_n,'./Public/Uploads/ChannelCount/');
      exit(json_encode(['success'=>'OK','filename'=>$filename_n,'message'=>$filename_n.'导出成功！']));
    }
  }
  /**
   * 财务历史操作记录
   */
  public function OrderHistoryFinance() {
    $this->Islogin();
    $order_mdb  = D('order');
    $order_data = $order_mdb->OrderHistoryFinance();
    $page = $order_data['page'];
    $page->setConfig('header','个会员');
    $this->assign('order_data',$order_data['data']);
    $this->assign('show',$page->show);
    $this->display('orderhistory');
  }
  /**
   * 财务还款记录
   */
  public function OrderRepayment(){
      $this->Islogin();
      $orderstatus = M("order_pay");
      $user        = M("user");
      $count= $orderstatus->count();// 查询满足要求的总记录数
      $Page = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数(25)
      $orderlist   = $orderstatus->order("create_time DESC")->limit($Page->firstRow.','.$Page->listRows)->select();
      foreach ($orderlist as $key => $value) {
          if($value['pay_month'] == "0"){
            $orderlist[$key]['pay_month'] = "(首付)";
          }
          $userlist = $user->where("id = ".$value['uid'])->find();
          $orderlist[$key]['fullanme']  = $userlist['fullanme'];
          $orderlist[$key]['tel']       = $userlist['tel'];
          $orderlist[$key]['banknum']   = $userlist['banknum'];
          $orderlist[$key]['bank']   = $userlist['bank'];
          $orderlist[$key]['pay_time']  = date("Y-m-d",$value['create_time']);
      }
      $this->assign('order_data',$orderlist);
      $this->assign('page',$Page->show());
      $this->display("FC_OrderRepayment");

  }
  /**
   * 订单不同状态显示不同信息
   */
  public function orderInformAtionStatus() {
    $this->Islogin();
    $data   = I('post.');
    $order  = D('Order');
    $res    = $order->getOrderInformAtionStatus($data);
    if($res){
      $result = $order->getModelStatus($res);
    }
    $this->ajaxReturn($result);
  }
  /**
   * 列表
   * @return [type] [description]
   */
    public function establishorder(){
      $this->Islogin();
        $Cars = D('Cars');
        $this->assign('Cars',$Cars->getCarsData());
        $this->display();
    }
    /**
     * 搜索手机号
     */
    public function findUser(){
      $this->Islogin();
        $data = I('post.');
        $User = M('User');
        $order = M('Order');
        $list = $User->where(array('tel'=>$data['tel']))->find();
        if($order->where(array('uid'=>$list['id']))->find()){
          echo "2";die;
        }
        if(!$list){
          echo "1";die;
        }
        $this->ajaxReturn(array('data'=>$list));
    }
    
    /**
     * 返回修改订单传送的值
     */
    public function saveOrder(){
      $this->Islogin();
      $data = I('post.');
      $order= D('Order');
      $Myinfo = D('Myinfo');
      $Myinfo = $Myinfo->getVehicle(true);
      $res    = $order->getSaveOrder($data);
      if ($res) {
        $res['vehicle']= $Myinfo;
        $this->ajaxReturn($res);
      }
    }
    /**
     * 等待签约订单列表
     */
    public function listOrder(){
      $this->Islogin();
      $order = D("Order");
      $admin = M("admin");
      $id    = session('lampzuo_id');
      $addres = $admin->where(array('id'=>$id))->find();
      $res   = $order->getListOrder($addres);
      $this->ajaxReturn($res);
    }
    /**
     * 订单数据并返回订单
     * @return [array] [res]
     */
    public function getDetaIls(){
      // session("lampzuo_id",null);
      $this->Islogin();
      $data  = I('get.');
      $admin = M("admin");
      $order = D("Order");
      $id    = session('lampzuo_id');
      $addres = $admin->where(array('id'=>$id))->find();
      $res    = $order->getListOrder($addres,$data);
      $result = $order->getModelStatus($res);
      $this->ajaxReturn($result);
    }
    /**
     * 查看订单被驳回原因
     */
    public function getReject(){
       $this->Islogin();
      $data = I("post.");
      $operation = M('order_operation');
      $res = $operation->where(array("orderid"=>$data['orderid'],"status"=>-2))->order("id DESC")->find();
      $this->ajaxReturn($res);
    }
    /**
     * 签约
     */
    public  function getSign(){
      $this->Islogin();
      $data = I('post.');
      $order= D('Order');
      $row  = $order->getPublicSign($data);
      if($row){
        return $this->ajaxReturn($row);
      }
    }
    /**
     * 确认签约
     */
    public function getConfirmSign(){
      $this->Islogin();
      $data     = I('post.');
      $order    = D('order');
      $morder   = M('order');
      $stockdetails= M('stock_details');
      $stockdeta= $stockdetails->where(array('id'=>$data['id'],'framenum'=>$data['framesizes'],'enginenum'=>$data['enginelist']))->find();
      if($stockdeta['status'] != 1){
         $this->ajaxReturn(array('ret'=>0,"msg"=>"对不起该发动机车辆刚已卖出!"));
      }
      $mod = $morder->where(array('contract'=>$data['contract']))->find();
      if($mod){
         $this->ajaxReturn(array('ret'=>0,"msg"=>"对不起合同号已存在!"));
      }
      $res = $order->getQianYue($data);
      if($res['withhold']=="ERROR"){
          $this->ajaxReturn($res);
      }
      if($res['success']=="ERROR"){
          $this->ajaxReturn($res);
      }
      if($res){
        $this->ajaxReturn(array('ret'=>1,"msg"=>"签约成功"));
      }else{
        $this->ajaxReturn(array('ret'=>0,"msg"=>"签约失败"));
      }
    }

    /**
     * 上牌页面加载
     * @return [type] [description]
     */
    public  function getShang(){
      $this->Islogin();
      $data = I('post.');
      $order= D('Order');
      $row  = $order->getPublicSign($data);
      if($row){
        return $this->ajaxReturn($row);
      }
    }

    /**
     * 上牌
     */
    public function getOntheCard(){
      $this->Islogin();
      $data     = I('post.'); 
      $morder   = M('order');
      $order    = D('order');
      $moer     = $morder->where('car_num='.$data['carnum'])->find();
      // $framenum  = $morder->where('framenum='.$data['framenum'])->find();
      // $enginenum = $morder->where('enginenum='.$data['enginenum'])->find();
      if($moer){
         $this->ajaxReturn(array('ret'=>0,"msg"=>"车牌号已存在!"));
      }
      $res     = $order->getShangPai($data);
      if($res){
        $this->ajaxReturn(array('ret'=>1,"msg"=>"上牌成功"));
      }else{
        $this->ajaxReturn(array('ret'=>0,"msg"=>"上牌失败"));
      }
    }

    /**
     * 返回查看信息
     */
    public function isGetOrderDetalis(){
      $this->Islogin();
      $data = I('post.');
      $order= D('order');
      $res  = $order->getPublicSign($data);
      if($res){
          $res['create_time'] = date('Y-m-d H:i:s',$res['create_time']);
      }
      $this->ajaxReturn($res);
    }
    /**
     * 图片处理
     * @param  [type] $data   [description]
     * @param  [type] $resuid [description]
     * @return [type]         [description]
     */
    public function webfileupload($data,$resuid){
            $arr    = array();//身份证
            $jszarr = array();//驾驶证
            $gzarr  = array();//工作证明
            $zxarr  = array();//征信报告
            $yharr  = array();//银行流水
            $config = C('DOWNLOAD_UPLOAD');
            $config['rootPath'] =  './Public/Image/Createanorder/'.$resuid.'/';
            if(!is_dir($config['rootPath'])){
                mkdir($config['rootPath']);
            }
            if($data['gzzm']){
              $config['subName']  = "workproof_url";
              $upload = new \Think\Upload($config);// 实例化上传类
              $info=array();
              foreach ($data['gzzm']['name'] as $key=>$value){
                    $file1=array();
                    $file1["gzzm"]['name']=$value;
                    $file1["gzzm"]['type']=$data['gzzm']["type"][$key];
                    $file1["gzzm"]['tmp_name']=$data['gzzm']["tmp_name"][$key];
                    $file1["gzzm"]['error']=$data['gzzm']["error"][$key];
                    $file1["gzzm"]['size']=$data['gzzm']["size"][$key];
                    $info   =   $upload->upload($file1);
                    array_push($gzarr,$config['rootPath'].$info['gzzm']['savepath'].$info['gzzm']['savename']);
                }
            }
            if($data['zx']){
              $config['subName']  =  "creditreport_url";
              $upload = new \Think\Upload($config);// 实例化上传类
              $info=array();
              foreach ($data['zx']['name'] as $key=>$value){
                    $file1=array();
                    $file1["zx"]['name']=$value;
                    $file1["zx"]['type']=$data['zx']["type"][$key];
                    $file1["zx"]['tmp_name']=$data['zx']["tmp_name"][$key];
                    $file1["zx"]['error']=$data['zx']["error"][$key];
                    $file1["zx"]['size']=$data['zx']["size"][$key];
                    $info   =   $upload->upload($file1);
                    array_push($zxarr,$config['rootPath'].$info['zx']['savepath'].$info['zx']['savename']);
                }
            }
            if($data['yhls']){
              $config['subName']  =  "bankflow_url";
              $upload = new \Think\Upload($config);// 实例化上传类
              $info=array();
              foreach ($data['yhls']['name'] as $key=>$value){
                    $file1=array();
                    $file1["yhls"]['name']=$value;
                    $file1["yhls"]['type']=$data['yhls']["type"][$key];
                    $file1["yhls"]['tmp_name']=$data['yhls']["tmp_name"][$key];
                    $file1["yhls"]['error']=$data['yhls']["error"][$key];
                    $file1["yhls"]['size']=$data['yhls']["size"][$key];
                    $info   =   $upload->upload($file1);
                    array_push($yharr,$config['rootPath'].$info['yhls']['savepath'].$info['yhls']['savename']);
                }
            }
            if($data['sfz']){
              $config['subName']  =  "identify_url";
              $upload = new \Think\Upload($config);// 实例化上传类
              $info=array();
              foreach ($data['sfz']['name'] as $key=>$value){
                    $file1=array();
                    $file1["sfz"]['name']=$value;
                    $file1["sfz"]['type']=$data['sfz']["type"][$key];
                    $file1["sfz"]['tmp_name']=$data['sfz']["tmp_name"][$key];
                    $file1["sfz"]['error']=$data['sfz']["error"][$key];
                    $file1["sfz"]['size']=$data['sfz']["size"][$key];
                    $info   =   $upload->upload($file1);
                    array_push($arr,$config['rootPath'].$info['sfz']['savepath'].$info['sfz']['savename']);
                }
            }
            if($data['jsz']){
              $config['subName']  =  "driver_url";
              $upload = new \Think\Upload($config);// 实例化上传类
              $info=array();
              foreach ($data['jsz']['name'] as $key=>$value){
                    $file1=array();
                    $file1["jsz"]['name']=$value;
                    $file1["jsz"]['type']=$data['jsz']["type"][$key];
                    $file1["jsz"]['tmp_name']=$data['jsz']["tmp_name"][$key];
                    $file1["jsz"]['error']=$data['jsz']["error"][$key];
                    $file1["jsz"]['size']=$data['jsz']["size"][$key];
                    $info   =   $upload->upload($file1);
                    array_push($jszarr,$config['rootPath'].$info['jsz']['savepath'].$info['jsz']['savename']);
                }
            }
            $addarr= array(
                "identify_url"      => $arr,
                "driver_url"        => $jszarr,
                "workproof_url"     => $gzarr,
                "bankflow_url"      => $yharr,
                "creditreport_url"  => $zxarr,
              );
        return $addarr;
    }
    
    /**
     * 风控审核通过状态更改
     */
    public function riskEvaluate(){
      $this->Islogin();
      $data = I('post.');
      $order = D('Order');
      $aorder= M('Order')->where(array('orderid'=>$data['orderid']))->find();
      if($aorder['last_update'] != $aorder['create_time']){
        echo "2";die;
      }
      if($data['status']=='-2' || $data['status']=='-1' || $data['status']=='1'){
        $data['reject_remark'] = $data['remark'];
      }
      $res = $order->getSiskEvaluate($data);
      if($res){
         $this->ajaxReturn(array('ret'=>1,'msg'=>"状态操作成功"));
      }else{
         $this->ajaxReturn(array('ret'=>0,'msg'=>"状态操作失败"));
      }
    }

    /**
     * 财务确认收款
     */
    public function financeConfirm(){
      $this->Islogin();
      $data = I('post.');
      $order= D('Order');

      $res  = $order->getFinance($data);
      if($res === "6"){
         $this->ajaxReturn(array('ret'=>0,'msg'=>"对不起你不是财务人员无法操作"));
      }else if($res === "2"){
         $this->ajaxReturn(array('ret'=>0,'msg'=>"订单暂未签约。"));
      }
      if($res){
         $this->ajaxReturn(array('ret'=>1,'msg'=>"状态操作成功")); 
      }else{
         $this->ajaxReturn(array('ret'=>0,'msg'=>"状态操作失败"));
      }
    }

  /**
   * 渠道分润列表
   */
  public function channelprofit(){
    $this->Islogin();
    $order_mdb = D('order');
    $arrChannel=  $order_mdb->getWaynumMoney();
    $this->assign('channellist',$arrChannel);
    $this->display('channelprofit');
  }
  /**
   * 修改已打款状态
   */
  public function channelstatus(){
      $data = I('post.');
      $waynum = M('wayuser_pay');
      $admin  = M('admin');
      // $sess = session('lampzuo_id');
      $res = $admin->where(array('id'=>session('lampzuo_id')))->find();
      if(!$res){
        $this->Islogin();
      }
      $arr = array(
        'usernum' => $res['usernum'],
        'status' => $data['status'],
        );
      $res = $waynum->where(array('id'=>$data['id'],'waynum'=>$data['waynum']))->save($arr);
      if($res){
        $this->ajaxReturn(array('success'=>"OK",'status'=>1,'message'=>"操作成功"));
      }else{
        $this->ajaxReturn(array('success'=>"error",'status'=>2,'message'=>"操作失败"));
      }
  }
  /**
   * 已给渠道打款记录
   * @return [type] [description]
   */
  public function channelprofitlist(){
    $order = D('order');
    $adminid = session('lampzuo_id');
    $res = $order->getWaynumList($adminid);
    $this->assign('channellist',$res);
    $this->display();
  }

  /**
   * 消息提醒
   * @return [type] [description]
   */
  public function fkcallseven(){
        $orderremind   = M("order");
        $admin         = M('admin');
        $ordermonthpay = M('order_month_pay');
        $jdcwayuser    = M('wayuser');
        $addres = $orderremind->where("status = 0 or status = 3")->select();
        $adminaddres = $admin->where('id = '.session('lampzuo_id'))->find();
        if($adminaddres['position'] == "503"){
            $addres = $orderremind->where("(status = 0  or status = 3) and thirdparty_audit = 1")->select();
        }
        $datepath = "Public/CallAdmin/Risk";
        if(!ossGetObject($datepath))
        {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            $res=createObjectDir($datepath);
        }
        $arr = array(
            'pending'=>0, //等待审核数
            'repayment'=>0, //即将还款数
            'overdue'=>0, //逾期数
            'staymonytype'=>0,//代收款查看
            'admintype'=>$adminaddres['position'],//人员标识判断
            'channelPending'=>0,//渠道待审核
          );
        $paymone = $ordermonthpay->where('status <> 1')->select();
        foreach ($addres as $key => $value) {
            $fileName="Public/CallAdmin/Risk/".$adminaddres['tel'].$value['orderid'].".json";
            $result  = ossGetObject($fileName);
                if(!$result){
                  $data = array(
                    'pending'=>0, //等待审核数
                    'repayment'=>0, //即将还款数
                    'overdue'=>0, //逾期数
                    'staymonytype'=>0,//财务确认收款
                  );
                    if($value['status'] == "3" && $adminaddres['position'] == "6"){
                      $arr['staymonytype'] +=1;
                      $data['staymonytype'] =1;
                    }elseif($value['status'] == "0" || $value['status'] == "7"){
                        $time = time();
                        foreach ($paymone as $ke => $val) {
                          if($val['orderid'] == $value['orderid']){
                            if($val['pay_time'] < $time){
                                  $data['overdue'] = 1;
                                  $arr['overdue'] += 1;
                            }
                            if($val['pay_time']-(7*20*60*60) < $time){
                                  $arr['repayment'] +=1;
                                  $data['repayment'] =1;
                            }
                          }
                        }
                        $data['pending'] =1;
                        $arr['pending'] +=1;
                    }
                  $jsondata = json_encode($data);
                  ossPutObject($fileName,$jsondata);
              }else{
                  $jsonres = json_decode($result,true);
                  if($jsonres){
                      $arr['pending']   += $jsonres['pending'];
                      $arr['repayment'] += $jsonres['repayment'];
                      $arr['overdue']   += $jsonres['overdue'];
                  }
              
            }
        }
        //渠道消息提醒
        $callchenn = $jdcwayuser->where("status=1")->select();
        $channelpath = "Public/CallAdmin/ChannelRisk";
        if(!ossGetObject($channelpath))
        {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            $res=createObjectDir($channelpath);
        }
        $channarr = [];
        $fileName="Public/CallAdmin/ChannelRisk/".$adminaddres['tel'].".json";
        $result  = ossGetObject($fileName);
        foreach ($callchenn as $key => $value) {
          if($result){
            $jsonres = json_decode($result,true);
            foreach ($jsonres as $k => $v) {
              if($value['id'] == $v['id']){
                $arr['channelPending'] += $v['channelPending'];
              }
            }
          }else{
            $chenval['id'] = $value['id']; 
            $chenval['channelPending'] = 1;
            $arr['channelPending'] += 1;
            $channarr[] = $chenval;
          }
        }
        if(!$result){
            $jsondata = json_encode($channarr);
            ossPutObject($fileName,$jsondata);
        }
        $this->ajaxReturn($arr);
  }
  public function  editremind(){
    $call = M('order');
    $admin = M('admin');
    $jdcwayuser= M('wayuser');
    $typelist = I("post.data"); 
    $adminaddres = $admin->where('id = '.session('lampzuo_id'))->find();
    $callarr  = $call->select();
    foreach ($callarr as $key => $value) {
        $fileName="Public/CallAdmin/Risk/".$adminaddres['tel'].$value['orderid'].".json";
        $result  = ossGetObject($fileName);
        if($result){
          $jsonres = json_decode($result,true);
          if($result && $typelist == "1"){
              $jsonres['pending'] = 0;
              // $jsonres['pendigtype'] = 1;
          }else if($result && $typelist == "2"){
              $jsonres['repayment'] = 0;  
              // $jsonres['repaymenttype'] = 1;  
          }else if($result && $typelist == "3"){
              $jsonres['overdue'] = 0;  
              // $jsonres['overduetype'] = 1;  
          }else if($result && $typelist == "4"){
              $jsonres['staymonytype'] = 0;  
          }
          $jsondata = json_encode($jsonres);
          ossPutObject($fileName,$jsondata);
        }
    }
    $channName="Public/CallAdmin/ChannelRisk/".$adminaddres['tel'].".json";
    $reschann  = ossGetObject($channName);
    if($reschann){
      $jsonres = json_decode($reschann,true);
      foreach ($jsonres as $key => $value) {
        $jsonres[$key]['channelPending'] = 0;
      }
      $jsondata = json_encode($jsonres);
      ossPutObject($channName,$jsondata);
    }
    
    $this->ajaxReturn($typelist);
  }
  /**
   * [Call O端消息提醒]
   */
  public function Call()
  {
      $id = I('request.id');
      $admin_db = M('admin');
      $order_db = M('order');
      $wayuser_db = M('wayuser');
      $order_operation_db = M('order_operation');
      $order_month_pay_db = M('order_month_pay');
      $admin = $admin_db -> where(array('id' => $id)) -> find();
      switch($admin['position'])
      {
          case 1:
              $orderStatus = "status in (-2,-1,2,3,4,5,6)";
              break;
          case 2:
              $orderStatus = "status in (2,4)";
              break;
          case 3:
              $orderStatus = "status in (1,3,4,5,6)";
              break;
      }
      $path = 'Public/CallAdmin/GW';
      if (!ossGetObject($path)) {
          createObjectDir($path);
      }
      $data = [];$ordersid = '';
      if ($admin['position'] == 1) {
          $order_operation = $order_operation_db -> where(array('usernum' => $admin['usernum'], 'status' => 0)) -> select();
          $ordersid = "orderid in (".implode(',', array_column($order_operation, 'orderid')).")";
          $orders = $order_db -> where($ordersid." and ".$orderStatus) -> select();
          $result = $this -> adminCall($orders, $admin, $path);

          $wayuser = $wayuser_db -> where('admin_id='.$admin['id'].' and status <> 0 and status <> 1') -> select();
          $result2 = $this -> wayCall($admin, $wayuser, $path);

          $data = $result;
          $data['wayStatus'] = $result2;
      } else if ($admin['position'] == 2) {
          $orders = $order_db -> where("provinceid=".$admin['provinceid']." and ".$orderStatus) -> select();
          $result = $this -> adminCall($orders, $admin, $path);
          $data = $result;
      } else if ($admin['position'] == 3) {
          $orders = $order_db -> where("cityid=".$admin['cityid']." and ".$orderStatus) -> select();
          $result = $this -> adminCall($orders, $admin, $path);

          $gws = $admin_db -> where('id='.$admin['pid']) -> select();
          $admin_ids = "admin_id in (".implode(',', array_column($gws, 'id')).") and status == 0";
          $wayuser = $wayuser_db -> where($admin_ids) -> select();
          $result2 = $this -> wayCall($admin, $wayuser, $path);

          $data = $result;
          $data['wayStatus'] = $result2;
      }
      if ($admin['position'] == 4) {
          $orders = $order_db -> where(array('provinceid' => $admin['provinceid'])) -> select();
          $ordersid = "orderid in (".implode(',', array_column($orders, 'orderid')).")";
          $order_month_pay = $order_month_pay_db -> where($ordersid) -> select();
          $count = $this -> orderOverdueCall($orders, $order_month_pay, $admin, $path);
          $data['overdue'] = $count;
      } else if ($admin['position'] == 1) {
          $order_month_pay = $order_month_pay_db -> where($ordersid) -> select();
          $count = $this -> orderOverdueCall($orders, $order_month_pay, $admin, $path);
          $count1 = $this -> orderSevenCall($orders, $order_month_pay, $admin, $path);
          $data['overdue'] = $count;
          $data['seven'] = $count1;
      }
      $this -> ajaxReturn($data, 'JSONP');
  }

  public function wayCall($admin, $wayuser, $path)
  {
      $data = [];$content = []; $tag = true;
      $filename = $path.'/'.$admin['usernum'].$admin['tel'].'.json';
      foreach ($wayuser as $k => $v) {
          if (!doesObjectExist($filename)) {
              $content[$wayuser[$k]['id']] = [];
              $content[$wayuser[$k]['id']][$wayuser[$k]['status']] = 0;
              $data[$wayuser[$k]['status']] += 1;
          } else {
              if ($tag) {
                  $content = json_decode(ossGetObject($filename), true);
              }
              if ($content[$wayuser[$k]['id']][$wayuser[$k]['status']] == 0 && key_exists($wayuser[$k]['status'], $content[$wayuser[$k]['id']])) {
                  $data[$wayuser[$k]['status']] += 1;
              } else if (!key_exists($wayuser[$k]['status'],$content[$wayuser[$k]['id']])) {
                  $content[$wayuser[$k]['id']][$wayuser[$k]['status']] = 0;
                  $data[$wayuser[$k]['status']] += 1;
              }
              $tag = false;
          }
      }
      ossPutObject($filename, json_encode($content));
      return $data;
  }

  public function adminCall($orders, $admin, $path)
  {
      $data = [];
      foreach ($orders as $k => $v) {
          $content = [];
          $filename = $path.'/'.$admin['tel'].$orders[$k]['orderid'].'.json';
          if (!doesObjectExist($filename)) {
              $status = $orders[$k]['status'] == -1 || $orders[$k]['status'] == -2;
              if ((time() - $orders[$k]['create_time']) < 300 && $status) continue;
              $content[$orders[$k]['status']] = 0;
              $data[$orders[$k]['status']] += 1;
              ossPutObject($filename, json_encode($content));
          } else {
              $content = json_decode(ossGetObject($filename), true);
              foreach ($content as $key => $value) {
                  if ($orders[$k]['status'] == $key && $value == 0) {
                      $data[$orders[$k]['status']] += 1;
                  } else if (!key_exists($orders[$k]['status'],$content)) {
                      $data[$orders[$k]['status']] += 1;
                      $content[$orders[$k]['status']] = 0;
                  }
              }
              ossPutObject($filename, json_encode($content));
          }
      }
      return $data;
  }

  public function orderOverdueCall($orders, $order_month_pay, $admin, $path)
  {
      $count = 0;
      foreach ($orders as $key => $value) {
          $overdue = [];
          $filename = $path.'/'.$admin['tel'].$orders[$key]['orderid'].'.json';
          if (!doesObjectExist($filename)) {
              foreach ($order_month_pay as $k => $v) {
                  if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                      if ($order_month_pay[$k]['overdue_status'] == 1) {
                          $overdue[$order_month_pay[$k]['pay_month']] =  0;
                          $count += 1;
                      }
                  }
              }
              ossPutObject($filename, json_encode(['overdue' => $overdue]));
          } else {
              $result = json_decode(ossGetObject($filename), true);
              if (key_exists('overdue', $result)) {
                  $content = $result['overdue'];
                  foreach ($order_month_pay as $k => $v) {
                      if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                          $pay_month = $order_month_pay[$k]['pay_month'];
                          if ($order_month_pay[$k]['overdue_status'] == 1 && !key_exists($pay_month, $content)) {
                              $content[$pay_month] = 0;
                              $count += 1;
                          } else if (key_exists($pay_month, $content) && $content[$pay_month] == 0) {
                              $count += 1;
                          }
                      }
                  }
                  $result['overdue'] = $content;
              } else {
                  $overdue = [];
                  foreach ($order_month_pay as $k => $v) {
                      if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                          $pay_month = $order_month_pay[$k]['pay_month'];
                          if ($order_month_pay[$k]['overdue_status'] == 1) {
                              $overdue[$pay_month] = 0;
                              $count += 1;
                          }
                      }
                  }
                  $result['overdue'] = $overdue;
              }
              ossPutObject($filename, json_encode($result));
          }
      }
      return $count;
  }
  public function orderSevenCall($orders, $order_month_pay, $admin, $path)
  {
        $count = 0;
        foreach ($orders as $key => $value) {
            $overdue = [];
            $filename = $path.'/'.$admin['tel'].$orders[$key]['orderid'].'.json';
            if (!doesObjectExist($filename)) {
                foreach ($order_month_pay as $k => $v) {
                    if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                        $time = $order_month_pay[$k]['pay_time'] - time();
                        if ($time <= 604800 && $time >= 0) {
                            $overdue[$order_month_pay[$k]['pay_month']] =  0;
                            $count += 1;
                        }
                    }
                }
                ossPutObject($filename, json_encode(['seven' => $overdue]));
            } else {
                $result = json_decode(ossGetObject($filename), true);
                if (key_exists('seven', $result)) {
                    $content = $result['seven'];
                    foreach ($order_month_pay as $k => $v) {
                        if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                            $time = $order_month_pay[$k]['pay_time'] - time();
                            $pay_month = $order_month_pay[$k]['pay_month'];
                            if ($time <= 604800 && $time >= 0 && !key_exists($pay_month, $content)) {
                                $content[$pay_month] = 0;
                                $count += 1;
                            } else if (key_exists($pay_month, $content) && $content[$pay_month] == 0) {
                                $count += 1;
                            }
                        }
                    }
                    $result['seven'] = $content;
                } else {
                    $overdue = [];
                    foreach ($order_month_pay as $k => $v) {
                        if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                            $time = $order_month_pay[$k]['pay_time'] - time();
                            $pay_month = $order_month_pay[$k]['pay_month'];
                            if ($time <= 604800 && $time >= 0) {
                                $overdue[$pay_month] = 0;
                                $count += 1;
                            }
                        }
                    }
                    $result['seven'] = $overdue;
                }
                ossPutObject($filename, json_encode($result));
            }
        }
        return $count;
  }

  public function updateCall()
  {
      $id = I('request.id');
      $status = I('request.status');
      $name = I('request.name');
      $admin_db = M('admin');
      $order_db = M('order');
      $wayuser_db = M('wayuser');
      $order_operation_db = M('order_operation');
      $admin = $admin_db -> where(array('id' => $id)) -> find();
      if ($admin['position'] == 1) {
          $order_operation = $order_operation_db -> where(array('usernum' => $admin['usernum'], 'status' => 0)) -> select();
          $ordersid = "orderid in (".implode(',', array_column($order_operation, 'orderid')).")";
          $orders = $order_db -> where($ordersid) -> select();
          $wayuser = $wayuser_db -> where('admin_id='.$admin['id'].' and status <> 0 and status <> 1') -> select();
      } else if ($admin['position'] == 2) {
          $orders = $order_db -> where("provinceid=".$admin['provinceid']) -> select();
      } else if ($admin['position'] == 3) {
          $orders = $order_db -> where("cityid=".$admin['cityid']) -> select();
          $gws = $admin_db -> where('id='.$admin['pid']) -> select();
          $admin_ids = "admin_id in (".implode(',', array_column($gws, 'id')).") and status=1";
          $wayuser = $wayuser_db -> where($admin_ids) -> select();
      } else if ($admin['position'] == 4) {
          $orders = $order_db -> where("provinceid=".$admin['provinceid']) -> select();
      }
      $path = 'Public/CallAdmin/GW';
      $count = 0;
      if ($name == 'order') {
          foreach ($orders as $k => $v) {
              $filename = $path.'/'.$admin['tel'].$orders[$k]['orderid'].'.json';
              if (doesObjectExist($filename)) {
                  $content = json_decode(ossGetObject($filename), true);
                  if (is_array($content[$status])) {
                      foreach ($content[$status] as $key => $value) {
                          $content[$status][$key] = 1;
                          $count += 1;
                      }
                      ossPutObject($filename, json_encode($content));
                      continue;
                  }
                  if (key_exists($status, $content)) {
                      $content[$status] = 1;
                      $count += 1;
                  }
                  ossPutObject($filename, json_encode($content));
              }
          }
      }
      if (($admin['position'] == 1 || $admin['position'] == 3) && $name == 'wayuser') {
          $filename = $path.'/'.$admin['usernum'].$admin['tel'].'.json';
          if (doesObjectExist($filename)) {
              $content = json_decode(ossGetObject($filename), true);
              foreach ($wayuser as $k => $v) {
                  if ($content[$wayuser[$k]['id']][$status] == 0 && key_exists($status, $content[$wayuser[$k]['id']])) {
                      $content[$wayuser[$k]['id']][$status] = 1;
                      $count += 1;
                  }
              }
              ossPutObject($filename, json_encode($content));
          }
      }
      $this -> ajaxReturn(['status' => $status, 'count' => $count, 'msg' => $name], 'JSONP');
  }

}